package xyz.lament.springehcache;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UseCacheService
{
	public UseCacheService()
	{
		UserBean initUser1 = new UserBean();
		initUser1.setUid("1");
		initUser1.setName("Natalie Portman");
		initUser1.setAge(35);
		UserStore.setUser(initUser1);
		
		UserBean initUser2 = new UserBean();
		initUser2.setUid("2");
		initUser2.setName("Keira Knightley");
		initUser2.setAge(31);
		UserStore.setUser(initUser2);
		
		UserBean initUser3 = new UserBean();
		initUser3.setUid("3");
		initUser3.setName("Gal Gadot");
		initUser3.setAge(31);
		UserStore.setUser(initUser3);
	}
	
	@Cacheable(value="myCache")	
	public UserBean getUser(String uid) {
		UserBean serviceUser = UserStore.getUser(uid);
		System.out.println("no cache for this user, read from userStore. user: " + serviceUser);
		return serviceUser;
	}
	
	@CacheEvict(value="myCache", key="#user.uid")
	public void putUser(UserBean user)
	{
		UserStore.setUser(user);
		System.out.println("remove from cache if exist. user: " + user);
	}

	@CacheEvict(value="myCache")
	public void deleteUser(String uid) {
		UserStore.deleteUser(uid);
		System.out.println("remove from cache if exist. user's uid: " + uid);
	}
}
